package com.kinon.ceshiaccount.service;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by lhqq on 2017-12-01.
 */

public class AdImageService extends Service {
    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    String newpath = Environment.getExternalStorageDirectory().getPath();
    private boolean isNewImage = true;
    private ResponseBody body;
    //    private String url="http://e.hiphotos.baidu.com/zhidao/pic/item/d000baa1cd11728b43937b8fc8fcc3cec2fd2ce4.jpg";
    private String url = "http://pic02.keyinong.com/product/pic/20180103163741_96171.png";
    //    private String url="";
    private Context context;
    private Handler myHandler = new Handler();
    private Runnable adRunnable = new Runnable() {
        @Override
        public void run() {
            Log.e("lh", "adRunnable== ");
//            downLoadAdImage();
//            Bitmap bitmap = getPic(url); //下载
//            onSaveBitmap(bitmap, AdImageService.this);//保存到本地
//            createFile();
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("lh", "onBind====");
        return null;
    }

    @Override
    public void onCreate() {
        Log.e("lh", "onBind====");
        super.onCreate();
    }

    //    public static void verifyStoragePermissions(Activity activity) {
//        // Check if we have write permission
//        int permission = ActivityCompat.checkSelfPermission(activity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//            // We don't have permission so prompt the user
//            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
//                    REQUEST_EXTERNAL_STORAGE);
//        }
//    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("lh", "onStartCommand====");
//        getImage();

//        myHandler.post(adRunnable);
//        url=intent.getStringExtra("imgurl");
        context = this;
        new Thread(adRunnable).start();
        return super.onStartCommand(intent, flags, startId);
    }

    private void getImage() {
        Call<ResponseBody> call = HttpManage.getRequestApi().downloadImg(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                body = response.body();
                myHandler.post(adRunnable);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("lh", "serviceonDestroy== ");
        myHandler.removeCallbacks(adRunnable);

    }

    private void createFile() {
        String filepath = Environment.getExternalStorageDirectory()
                .getPath() + "/account_app/settle2.txt";
        File mfile = new File(filepath);
        if (mfile.exists()) { //判断文件是否存在
            mfile.delete(); //删除
        }
        try {
            mfile.createNewFile(); //创建文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void downLoadAdImage() {
        Log.e("lh", "== " + SunmiImgPath.pathwelcom);
        Log.e("lh", "newpath== " + newpath);
        try {
            if (!isNewImage || body == null) {
                return;
            }
            Log.e("lh", "0== ");
            InputStream is = body.byteStream();
            File fileDr = new File(newpath);
            Log.e("lh", "0---1== ");
            if (!fileDr.exists()) {
                Log.e("lh", "0---2== ");
                fileDr.mkdir();
                Log.e("lh", "0---3== ");
            }
            Log.e("lh", "1== ");
            File file = new File(newpath, "caizhengting.png");
            Log.e("lh", "2== ");
            if (file.exists()) {
                file.delete();
                file = new File(newpath, "caizhengting.png");
//                file=new File(SunmiImgPath.sysPath,
//                        "caizhengting.png");
            }
            Log.e("lh", "3== ");
            FileOutputStream fos = new FileOutputStream(file);
            Log.e("lh", "4== ");
            BufferedInputStream bis = new BufferedInputStream(is);
            Log.e("lh", "5== ");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public Bitmap getPic(String url) {
        //获取okHttp对象get请求
        try {
            OkHttpClient client = new OkHttpClient();
            //获取请求对象
            Request request = new Request.Builder().url(url).build();
            //获取响应体
            ResponseBody body = client.newCall(request).execute().body();
            //获取流
            InputStream in = body.byteStream();
            //转化为bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(in);

            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    Android保存图片到系统图库：http://blog.csdn.net/xu_fu/article/details/39158747
    * */
    private void onSaveBitmap(final Bitmap mBitmap, final Context context) {
        // 第一步：首先保存图片
        //将Bitmap保存图片到指定的路径/sdcard/Boohee/下，文件名以当前系统时间命名,但是这种方法保存的图片没有加入到系统图库中
        String newpath = Environment.getExternalStorageDirectory().getPath();

//        File appDir = new File(Environment.getExternalStorageDirectory(), "/account");
        File appDir = new File(SunmiImgPath.sysPath);

        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, "/caizhengting.png");

        try {
            FileOutputStream fos = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 第二步：其次把文件插入到系统图库
        //            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//   /storage/emulated/0/Boohee/1493711988333.jpg

        // 第三步：最后通知图库更新
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
        //context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }

//    private void createFile(){
////        String pathwelcom2= Environment.getExternalStorageDirectory().getAbsolutePath() +"/com.account";
//        String pathwelcom2=  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) +"/com.account";;
//
//        Log.e("lh", "pathwelcom2------"+pathwelcom2 );
//        File mfile=new File(pathwelcom2);
//        if(mfile.exists()){ //判断文件是否存在
//            Log.e("lh", "文件存在------" );
//
//        }else{
//
//            Log.e("lh", "文件不存在------" );
////                mfile.createNewFile(); //创建文件
//            boolean isfile=mfile.mkdir(); //删除
//            if(isfile) {
//                Log.e("lh", "文件创建成功------");
//            }else{
//                Log.e("lh", "文件创建失败------");
//            }
//        }
//
//    }


}
